package activity.lsen.smartwsn.com.bluetoothdemo;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import activity.lsen.smartwsn.com.bluetoothdemo.adapter.ListViewAdapter;

public class MainActivity extends AppCompatActivity {

    private final static String TAG = "MainActivity";

    public final static UUID SERVICE_UUID = UUID
            .fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    public final static UUID TX_SERVICE_UUID = UUID
            .fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
    public final static UUID RX_SERVICE_UUID = UUID
            .fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
    private static final UUID CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID = UUID
            .fromString("00002902-0000-1000-8000-00805f9b34fb");

    private ListView listView;
    private Button scanButton;
    private Button motorButton;
    private Button motorMinButton;
    private TextView heartTv;
    private TextView accelerationTv;
    private TextView temperatureTv;
    private TextView pullTv;
    private TextView pressureTv;
    private TextView uitravioletTv;
    private TextView relaxTv;
    private TextView focusOnTv;
    private TextView deltaTv;
    private TextView thetaTv;
    private TextView lowAlphaTv;
    private TextView highAlphaTv;
    private TextView lowBateTv;
    private TextView highBateTv;
    private TextView lowGammaTv;
    private TextView midGammaTv;

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothDevice bluetoothDevice;
    private BluetoothManager bluetoothManager;
    private BluetoothGatt bluetoothGatt;
    private BluetoothGattCharacteristic txCharacteristic;
    private BluetoothGattCharacteristic rxCharacteristic;
    private List<BluetoothDevice> deviceList;
    private ListViewAdapter listViewAdapter;
    private boolean isScanning = false;
    private boolean isUart = false;
    private final static int dem=10000;
    private byte[] value = new byte[20];

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    listViewAdapter = new ListViewAdapter(MainActivity.this, deviceList);
                    listView.setAdapter(listViewAdapter);
                    break;
                case 2:
                    listViewAdapter.notifyDataSetChanged();
                    break;
                case 3:
                    switch (value[0]) {
                        case 0x01:
                            if (value[1] == 0x01) {
                                heartTv.setText(String.valueOf(value[2] >= 0 ? value[2] : value[2] + 256));
                            }
                            break;
                        case 0x02:

                            break;
                        case 0x03:
                            if (value[1] == 0x04) {
                                int i31 = value[2] >= 0 ? value[2] : value[2] + 256;
                                int i32 = value[3] >= 0 ? value[3] : value[3] + 256;
                                int i33 = value[4] >= 0 ? value[4] : value[4] + 256;
                                int i34 = value[5] >= 0 ? value[5] : value[5] + 256;
                                int acce = (i31 * 256) + (i32 * 256) + (i33 * 256) + i34;
                                accelerationTv.setText(String.valueOf(acce));
                            }
                            break;
                        case 0x04:
                            if (value[1] == 0x02) {
                                int i4 = value[2] >= 0 ? value[2] : value[2] + 256;
                                int i41 = value[3] >= 0 ? value[3] : value[3] + 256;
                                String str1=String.valueOf(i4);
                                String str2=String.valueOf(i41);
                                temperatureTv.setText(str1+"."+str2);
                            }
                            break;
                        case 0x05:
                            if (value[1] == 0x0e) {
                                int[] aj = new int[4];
                                int k = 0;
                                for (int i = 0; i < 12; i += 3) {
                                    int int_0 = value[i + 3] >= 0 ? value[i + 3]
                                            : value[i + 3] + 256;
                                    int int_1 = value[i + 4] >= 0 ? value[i + 4]
                                            : value[i + 4] + 256;
                                    int int_2 = value[i + 5] >= 0 ? value[i + 5]
                                            : value[i + 5] + 256;
                                    aj[k] = (int_0 * 256) + (int_1 * 256) + int_2;
                                    k++;
                                }
                                if (value[2] == 0x00) {
                                    relaxTv.setText(String.valueOf(value[15]));
                                    deltaTv.setText(String.valueOf(aj[0]));
                                    thetaTv.setText(String.valueOf(aj[1]));
                                    lowAlphaTv.setText(String.valueOf(aj[2]));
                                    highAlphaTv.setText(String.valueOf(aj[3]));
                                } else if (value[2] == 0x01) {
                                    focusOnTv.setText(String.valueOf(value[15]));
                                    lowBateTv.setText(String.valueOf(aj[0]));
                                    highBateTv.setText(String.valueOf(aj[1]));
                                    lowGammaTv.setText(String.valueOf(aj[2]));
                                    midGammaTv.setText(String.valueOf(aj[3]));
                                }
                            }
                            break;
                        case 0x06:
                            if (value[1] == 0x02) {
                                String i6 =String.valueOf ((value[2] >= 0 ? value[2] : value[2] + 256));
                                String i61 =String.valueOf(( value[3] >= 0 ? value[3] : value[3] + 256));
                                pullTv.setText(i6 + "." + i61);
                            }
                            break;
                        case 0x07:
                            if (value[1] == 0x02) {
                                String i7 =String.valueOf( value[2] >= 0 ? value[2] : value[2] + 256);
                                String  i71 =String.valueOf( value[3] >= 0 ? value[3] : value[3] + 256);
                                pressureTv.setText((i7 + "." + i71));
                            }
                            break;
                        case 0x08:
                            if (value[1] == 0x02) {
                                int i8 = value[2] >= 0 ? value[2] : value[2] + 256;
                                uitravioletTv.setText(String.valueOf(i8));
                            }
                            break;
                    }
                    break;
                default:
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        if (isBleEnabled()) {
            enableBluetooth();
        }
    }

    private void init() {
        deviceList = new ArrayList<>();
        focusOnTv = (TextView) findViewById(R.id.focuson);
        relaxTv = (TextView) findViewById(R.id.relax);
        deltaTv = (TextView) findViewById(R.id.delta);
        thetaTv = (TextView) findViewById(R.id.theta);
        lowBateTv = (TextView) findViewById(R.id.lowBate);
        highBateTv = (TextView) findViewById(R.id.highBate);
        lowGammaTv = (TextView) findViewById(R.id.lowGamma);
        midGammaTv = (TextView) findViewById(R.id.midGamma);
        lowAlphaTv = (TextView) findViewById(R.id.lowAlpha);
        highAlphaTv = (TextView) findViewById(R.id.highAlpha);
        heartTv = (TextView) findViewById(R.id.heart);
        pullTv = (TextView) findViewById(R.id.pull);
        uitravioletTv = (TextView) findViewById(R.id.uitraviolet);
        pressureTv = (TextView) findViewById(R.id.pressure);
        accelerationTv = (TextView) findViewById(R.id.acceleration);
        temperatureTv = (TextView) findViewById(R.id.temperature);
        listView = (ListView) findViewById(R.id.list_scan);
        scanButton = (Button) findViewById(R.id.scan);
        motorButton = (Button) findViewById(R.id.motor);
        motorMinButton = (Button) findViewById(R.id.motor_min);
        handler.sendEmptyMessage(1);

        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deviceList.removeAll(deviceList);
                showToast(getResources().getString(R.string.start_scan));
                startScan();
            }
        });

        motorButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                byte[] valBytes = new byte[20];
                valBytes[0] = 0x02;
                valBytes[1] = 0x02;
                valBytes[2] = 0x01;
                valBytes[3] = 0x06;
                writeCharacteristic(valBytes);
            }
        });

        motorMinButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                byte[] valBytes = new byte[20];
                valBytes[0] = 0x02;
                valBytes[1] = 0x02;
                valBytes[2] = 0x00;
                valBytes[3] = (byte) 200;
                writeCharacteristic(valBytes);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                stopScan();
                bluetoothDevice = deviceList.get(position);
                connectGatt(bluetoothDevice);
            }
        });
    }

    private boolean isBleEnabled() {
        bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled();
    }

    private void enableBluetooth() {
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 2);
        }
    }

    private void startScan() {
        UUID[] uuids = new UUID[1];
        uuids[0] = SERVICE_UUID;
        isScanning = true;
        bluetoothAdapter.startLeScan(uuids, scanCallback);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isScanning) {
                    stopScan();
                }
            }
        }, dem);
    }

    private void stopScan() {
        if (isScanning) {
            bluetoothAdapter.stopLeScan(scanCallback);
            isScanning = false;
            showToast(getResources().getString(R.string.stop_scan));
        }
    }

    private BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (device != null) {
                if (!deviceList.contains(device)) {
                    deviceList.add(device);
                }
                Log.i(TAG, device.getAddress());
                handler.sendEmptyMessage(2);
            }
        }
    };

    private void closeBluetoothGatt() {
        if (bluetoothGatt == null) {
            return;
        }
        bluetoothGatt.close();
        bluetoothGatt = null;
    }

    private void connectGatt(BluetoothDevice bluetoothDevice) {
        if (bluetoothGatt != null) {
            closeBluetoothGatt();
        }
        if (bluetoothGatt == null) {
            bluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this, false, bluetoothGattCallback);
        }

    }

    private BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (status == bluetoothGatt.GATT_SUCCESS) {
                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    bluetoothGatt.discoverServices();
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    closeBluetoothGatt();
                }
            } else {
                closeBluetoothGatt();
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            isUart = false;
            if (status == bluetoothGatt.GATT_SUCCESS) {
                List<BluetoothGattService> services = gatt.getServices();
                for (BluetoothGattService service : services) {
                    isUart = true;
                    txCharacteristic = service.getCharacteristic(TX_SERVICE_UUID);
                    rxCharacteristic = service.getCharacteristic(RX_SERVICE_UUID);
                }
                if (isUart) {
                    setCharacteristicNotification(txCharacteristic, true);
                }
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            if (characteristic.getUuid().equals(TX_SERVICE_UUID)) {
                value = new byte[20];
                for (int i = 0; i < value.length; i++) {
                    value[i] = characteristic.getValue()[i];
                }
                handler.sendEmptyMessage(3);
                Log.i(TAG, bytesToHexString(value));
            }
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);
        }

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            super.onReliableWriteCompleted(gatt, status);
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
        }

        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
        }
    };

    private boolean setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enable) {
        if (bluetoothGatt == null) {
            return false;
        }
        bluetoothGatt.setCharacteristicNotification(characteristic, enable);
        BluetoothGattDescriptor bluetoothGattDescriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
        bluetoothGattDescriptor.setValue(bluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        return bluetoothGatt.writeDescriptor(bluetoothGattDescriptor);
    }

    private boolean writeCharacteristic(byte[] value) {
        boolean isSend = false;
        if (bluetoothGatt != null && rxCharacteristic != null) {
            rxCharacteristic.setValue(value);
            isSend = bluetoothGatt.writeCharacteristic(rxCharacteristic);
        }
        return isSend;
    }


    public void showToast(final String messge) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast toast = Toast.makeText(getApplicationContext(), messge, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.BOTTOM, 0, 300);
                toast.show();
            }
        });
    }

    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    @Override
    protected void onDestroy() {
        closeBluetoothGatt();
        super.onDestroy();

    }
}
